﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using ColladaDotNet;
using ColladaDotNet.Scene;
using Microsoft.DirectX;

namespace BakalarskaPraca.Generation.Data
{
    public class Plant
    {
        public float X;
        public float Y;
        public float Z;
        private static Random _random = new Random();

        public Boolean Dead = false;
        
        public PlantData PlantData;

        public int Age = 0;
        public int LastReproductionCycle = 0;

        public void Grow(int iterations)
        {
            this.Age += iterations;
            if (this.Age > this.PlantData.MaxAge)
            {
                this.Dead = true;
            }
        }

        public bool CanReproduce()
        {
            return this.Age > this.PlantData.MinAgeForReproduction &&
                   this.Age - this.LastReproductionCycle > this.PlantData.ReproductionInterval;
        }

        public bool WillSurvive(int humidity)
        {
            return this.PlantData.MinHumidity <= humidity && 
                   this.PlantData.MaxHumidity >= humidity;
        }

        public void InsertPlantNode(Vector3 position, ColladaDocument document)
        {
            PlantModel model = PlantModel.GetPlantModel(this.PlantData, document);
            
            XElement elem = new XElement("node");
            elem.SetAttributeValue("type", "NODE");
            elem.SetAttributeValue("id", "plant_" + ("" + this.X + this.Y + this.Z).Replace('.','_'));
            
            XElement geoInstance = new XElement("instance_node");
            geoInstance.SetAttributeValue("url", "#" + model.Name);

            elem.Add(geoInstance);

            XmlReader reader = elem.CreateReader();
            XmlDocument doc = new XmlDocument();

            doc.Load(reader);

            XmlNode sceneNode = document.VisualScenes[0].Nodes[0].XmlElement.ParentNode;
            if (sceneNode == null || sceneNode.OwnerDocument == null)
            {
                throw new ArgumentException();
            }
            
            Node result = new Node(doc.DocumentElement, null);

            result.Transformations.Add(new RotationTransformation(result, 0, 0, 1, Plant._random.Next(360)));
            result.Transformations.Add(new TranslationTransformation(result, position.X, position.Y, position.Z));

            sceneNode.AppendChild(sceneNode.OwnerDocument.ImportNode(doc.DocumentElement, true));
            document.VisualScenes[0].Nodes.Add(result);
            
        }
    }
}
